'''
Created on 09.08.2010

@author: Valiuh Anton - valiuh@gmail.com

		This program is computer video game based on simple facial
		detection method. This method use on skin color model.
		Program do not used any computer vision library like OpenCV,
		or other learning based classifier such as Haar-like features,
		neural network etc. You can find more detailed description
		of the method here -
		http://blogs.msdn.com/b/coding4fun/archive/2010/03/24/9984015.aspx

		Good luck!
'''

from pygame import *
import sys
import Image
from VideoCapture import Device
import ImageDraw
import psyco
import random
import time

from GameObj import GameObj
from Find_FaceObj import Find_FaceObj


if __name__ == '__main__':
	
	
	#main_path = sys.argv[0][0:sys.argv[0].rfind('\\')] +'\\path.ini'
	#f = open(main_path, 'r')
	
	
	psyco.full() # begin program boosting by psyco
	time_begin= time.clock() # init of start timer
	cam = Device() # new vebcam devise

	input_buf = cam.getImage() # get first frame from veb cam
	# begin of initialization of veb cam
	for i in range(2000):
		input_buf = cam.getImage()
		print "init cam= ", i, " ms"
	# after initialization of veb cam, perform resizing of first input frame
	input_image=input_buf.resize((100,80))
	# get width, height of first input frame
	width, height = input_image.size
	size = input_image.size
	# creating new cbcr and binary buffer images for show and save results of color spase transforms
	cbcrIm = Image.new("RGB", size) # buffer image for YCbCr color space
	BinIm = Image.new("L", size) # buffer image for binary (grey scale) color space

	Face_Filter = Find_FaceObj(width, height) # creating new object for finding faces

	rgb = Face_Filter.InitMatrixRGB(width,height) # initialization matrix for RGB image operations
	cbcr = Face_Filter.InitMatrixRGB(width,height) # initialization matrix for YCbCr image operations
	bin = Face_Filter.InitMatrixBin(width,height) # initialization matrix for Binary image (grey scale) operations

	rgb = Face_Filter.Image_To_Matrix(rgb,input_image) # convert first input frame into RGB matrix
	cbcr = Face_Filter.RGBMat_To_CbCrMat(rgb,cbcr) # convert data from RGB matrix into YCbCr matrix
	bin = Face_Filter.CbCrMat_To_BinMat(cbcr,bin) # convert data from YCbCr matrix into Binary matrix

	#input_image.save('C:\\Python26\\begin.jpg',"JPEG") # save first input frame in to hard drive

	start_coord = Face_Filter.CalcHists_Find_Face(bin,input_image) # calculation of start position of face in front of veb cam

	init() # initialization of PyGame for game GUI.
	screen = display.set_mode((640, 480)) # Creatinn of main screen window of game.
	display.set_caption('example') # Creatinn a caption of main game window.
	background = image.load('C:\\Python26\\background.bmp') # load background of main game window
	screen.blit(background, (0,0)) # set background of main game window and update window

	plane = image.load('C:\\Python26\\d.bmp') # load of herois plane image texture
	Eplane = image.load('C:\\Python26\\d2.bmp') # load of enemys plane image texture

	x = GameObj(plane, 200, 80, 5) # create herois plane object
	Enemy=[] # init array of enemy plane objects

	# create enemy plane objects
	for i in range(10):
		Enemy.append(GameObj(Eplane, random.randint(10,470), random.randint(300,600), random.randint(2,6)))

	screen.blit(x.img, x.pos) # set herois plane in main game window and update window

	# set enemys plane in main game window and update window
	for enem in Enemy:
		screen.blit(enem.img, enem.pos)

	# begin of main program loop
	while 1:

		# begin of key analyse loop
		for i in event.get():
			if i.type == QUIT: # if pressed esc, or alt+F4 - program quit
				sys.exit()

		input_buf = cam.getImage()	# get next frame from veb cam
		input_image=input_buf.resize((100,80))	# perform resizing of next input frame

		rgb = Face_Filter.Image_To_Matrix(rgb,input_image) # convert next input frame into RGB matrix
		cbcr = Face_Filter.RGBMat_To_CbCrMat(rgb,cbcr) # convert data from RGB matrix into YCbCr matrix
		bin = Face_Filter.CbCrMat_To_BinMat(cbcr,bin) # convert data from YCbCr matrix into Binary matrix

		BinIm=Face_Filter.Matrix_To_Image(bin,BinIm) # back convert data from Binary matrix in to binary image
		BinIm.save('C:\\Python26\\grey.jpg',"JPEG") # save result binary image into hard drave

		res = Face_Filter.CalcHists_Find_Face(bin,input_image) # calculation of new position of face in front of veb cam

		Image = image.load('C:\\Python26\\work.jpg') # load image width finding fase on it
		Grey =  image.load('C:\\Python26\\grey.jpg') # load image in gray scale (binary image)

		screen.blit(Grey, (540,400)) # set image width finding fase in main game window
		screen.blit(Image, (540,320)) # set image in gray scale in main game window
		display.flip() # update main window

		# loop for move enemy planes
		for enem in Enemy:
			screen.blit(background, enem.pos, enem.pos) # set background
			enem.move(273) # move plain in new position up
			screen.blit(enem.img, enem.pos) # set enymy plain in main game window
			display.flip() # update main window


		if res[0]<10: # if fail measu => ignore it
			res[0]=10
		else: # if measu 'ok' =>
			screen.blit(background, x.pos, x.pos)
			if res[0]>start_coord[0]: #if measu new face coord > srart fase coord => face move right => plain must move right
				#pass
				x.move(275) # set plain move right (275 - K_RIGHT)
			if res[0]<start_coord[0]: #if measu new face coord < srart fase coord => face move left => plain must move left
				#pass
				x.move(276) # set plain move left (276 - K_LEFT)

			# loop for compare enemy planes coord and herois plane coord
			for enem in Enemy:

				if abs(x.pos[1]-enem.pos[1])<30: #if enemy plane X coord ~ X herois plane coord
					if abs(x.pos[0]-enem.pos[0])<30: #and if enemy plane Y coord ~ Y herois plane coord
						#than crash herois plane width enemy plane
						print "crash!!!!", x.pos[0], enem.pos[0], x.pos[1], enem.pos[1] # print enemy plane  coord and herois plane coord
						print "crash!!!!", (x.pos[0]-enem.pos[0]),(x.pos[1]-enem.pos[1])

						BOOMImage =  image.load('C:\\Python26\\boom.bmp') # load image width explose image
						BOOM = GameObj(BOOMImage, x.pos[0], x.pos[1], 0) # set explose image in main game window on position where was herois plane
						screen.blit(BOOM.img, BOOM.pos)
						display.flip() # update main window
						time.sleep(3) # set time delay before program quit
						sys.exit() # program quit

				# if no crash =>
				if enem.pos[1]<-30: # if enemy plane out of main window=>
					# set position of new enemys plane
					enem.pos[1] = random.randint(690,700)
					enem.pos[0] = random.randint(10,470)
				print enem.pos[0], enem.pos[1]


			screen.blit(x.img, x.pos)
			display.flip()

		print res
		time_end= time.clock() - time_begin
		print "ok, time= ", time_end

